import React, { Component } from "react";
// ant
import { Modal, Table, Form, Radio, Button, message } from "antd";
// API
// import { AliyunEcsListApi } from "@/api/raycloud";
import http from '../../../utils/request';
import axios from "axios";
// 组件
import { generateRamStr } from '../../../utils/validate'
// import FormCom from "@c/form/Index";

const options_month = [
    { label: "1", value: 1 },
    { label: "2", value: 2 },
    { label: "3", value: 3 },
    { label: "4", value: 4 },
    { label: "5", value: 5 },
    { label: "6", value: 6 },
    { label: "7", value: 7 },
    { label: "8", value: 8 },
    { label: "9", value: 9 }
]
const options_year = [
    { label: "1", value: 12 },
    { label: "2", value: 24 },
    { label: "3", value: 36 }
];

class RenewModal extends Component {
    constructor(props){
        super(props);
        this.state = {
            client_token: null,
            isModalVisible: false,
            isTableloading: false,
            ecs_id: "",
            radio_value: 1,
            discount_price: 0,  // 折扣
            original_price: 0, // 原价  
            trade_price: 0, // 最终价
            formLayout: {
                labelCol: { span: 2 },
                wrapperCol: { span: 22, offset: 1 }
            },
            // formItem: [
            //     { 
            //         type: "RadioButton",
            //         label: "续费时长", 
            //         name: "Period", 
            //         required: true, 
            //         style: { width: '100%' },
            //         options: [
            //             { label: "1m", value: "1" },
            //             { label: "3m", value: "3" },
            //             { label: "6m", value: "6" },
            //             { label: "9m", value: "9" },
            //             { label: "1yr", value: "12" },
            //             { label: "3yr", value: "36" },
            //             { label: "2yr", value: "48" },
            //         ],
            //     },
            // ],
            tableColumns: [
                    {
                      title: '实例ID/名称',
                      key: 'InstanceId',
                      dataIndex: 'InstanceId',
                      render: (text, rowData) => {
                        return (
                            <div>
                                {rowData.instance_id}
                                <br></br>
                                {rowData.instance_name}
                            </div>
                        )
                      }
                    },
                    {
                      title: '规格',
                      dataIndex: 'instance_type',
                      key: 'instance_type',
                      render: (text, rowData) => {
                        return (
                            <div>
                                {rowData.cpu} vCPU {rowData.memory/1024} GiB
                                <br></br>
                                ({rowData.instance_type})
                            </div>
                        )
                      }
                    },
                    // {
                    //   title: '基础带宽',
                    //   dataIndex: 'address',
                    //   key: 'address',
                    // },
                    {
                        title: '到期时间',
                        key: 'expired_time',
                        dataIndex: 'expired_time',
                        render: (text, rowData) => {
                            return (
                                <div>
                                    {/* {rowData.StartTime}
                                    <br></br> */}
                                    {rowData.expired_time}
                                </div>
                            )}
                    },
                    {
                        title: '价格',
                        key: 'age',
                        render: (text) => {
                            return (
                                <div>
                                    <span style={{color: '#f60'}}>￥ {this.state.trade_price}</span>
                                    <br/>
                                    {this.state.discount_price > 0 ? <span style={{color: '#2f7d0d'}}>省: ￥ {this.state.discount_price}</span> : ''}
                                </div>
                            )}
                    }
                ],
            tableData: null
        }
    }
    componentDidMount(){
        this.props.onRef(this);
    }

    // onFormRef = (ref) => {
    //     this.child = ref;
    // }

    // 关闭弹窗
    handleCancel = () => {
        this.setState({
            isModalVisible: false,  // 关闭弹窗
            radio_value: 1,   //  还原表单
            trade_price: 0,
            discount_price: 0
        })
    }
    
    /** 弹窗 */
    visibleModal = (params) => {
        console.log(params)
        this.setState({
            isModalVisible: params.status,
            ecs_id: params.ecs_id,
            client_token: generateRamStr(16)  // 保证幂等性
        }, () => {
            this.getDetailed();
            console.log(this.state)
        })
    }
    /** ecs详情 包括初始价格 并发查询*/
    getDetailed = () => {
        if(!this.state.ecs_id) { return false; }
        this.setState({ isTableloading: true });
        // 并发
        axios.all(
            [
                // AliyunEcsListApi({ecs_id: this.state.ecs_id}),
                http.get('/machine', {params: { instance_id: this.state.ecs_id }}),
                http.get('/aliyun/renewal_price', {params: { ecs_id: this.state.ecs_id, Period: 1 }}),
            ]
        ).then(axios.spread( (resp_ecs, resp_price) => {
            console.log(resp_ecs, resp_price)
            const data_ecs = resp_ecs.data.data.items;
            const data_price = resp_price.data.data;
            this.setState({
                tableData: data_ecs,
                trade_price: data_price.TradePrice,
                discount_price: data_price.DiscountPrice,
                original_price: data_price.OriginalPrice,
                isTableloading: false
            })
        }))
        // AliyunEcsListApi({ecs_id: this.state.ecs_id}).then(response => {
        //     const data = response.data.data.items;
        //     console.log(data)
        //     this.setState({
        //         tableData: data,
        //         isTableloading: false
        //     })
        // })
        // 初始价格
        // http.get('/aliyun/renewal_price',
        //          {params: { ecs_id: this.state.ecs_id, Period: 1 }
        //         }).then(response=>{
        //             const resp = response.data.data;
        //             console.log(response.data.data)
        //             this.setState({
        //                 trade_price: resp.TradePrice,
        //                 discount_price: resp.DiscountPrice,
        //                 original_price: resp.OriginalPrice
        //             })
        // })
    }

    onBlurEvent = (e) => {
        const value = e.currentTarget.value;
        if(value) {
            this.updateItem(value ? false : true);
            return false;
        }
    }
    // 提交表单按钮
    handlerFormSubmit= (value) => {
        const requestData = {
            client_token: this.state.client_token,  // 保证幂等性
            ecs_id: this.state.ecs_id,
            Period: value.Period ? value.Period : 1     // 参数PeriodUnit默认值为Month。Period取值为：1~12, 24, 36, 48, 60
        };
        console.log('renewModal payload ===>', requestData)
        // 续费api
        http.post('/aliyun/ecs/renew', requestData).then(response=> {
            const responseData = response.data;
            // 提示
            message.info(responseData.msg);
            // 关闭弹窗
            this.handleCancel(false);
        }).catch()
    }

    onChangeRadio = (e) => {
        console.log(e.target.value)
        this.setState({ 
            radio_value: e.target.value,
            trade_price: "正在计算价格...",
            discount_price: ''
        })
        // 价格查询api
        http.get('/aliyun/renewal_price',
                 {params: { ecs_id: this.state.ecs_id, Period: e.target.value}
                }).then(response=>{
                    // Currency: "CNY"
                    // DiscountPrice: 0  折扣
                    // OriginalPrice: 403  
                    // TradePrice: 403  最终价
                    const resp = response.data.data;
                    console.log(response.data.data)
                    this.setState({
                        trade_price: resp.TradePrice,
                        discount_price: resp.DiscountPrice,
                        original_price: resp.OriginalPrice
                    })
        })
    }

    render(){
        const { isTableloading } = this.state;
        return (
            <Modal title="续费信息" width='800px' visible={this.state.isModalVisible} footer={null} onCancel={this.handleCancel}>
                <Table columns={this.state.tableColumns} dataSource={this.state.tableData} pagination={false} loading={isTableloading}></Table>
                <Form onFinish={this.handlerFormSubmit} {...this.state.formLayout} style={{ marginTop: '40px'}}>
                    <Form.Item label="续费时长 " name="Period">
                        <span>
                    <Radio.Group
                        options={options_month}
                        onChange={this.onChangeRadio}
                        value={this.state.radio_value}
                        optionType="button"
                        buttonStyle="solid"
                        /> 个月 
                    <Radio.Group
                        options={options_year}
                        onChange={this.onChangeRadio}
                        value={this.state.radio_value}
                        optionType="button"
                        buttonStyle="solid"
                        /> 年
                        </span>
                    </Form.Item>
                    <Form.Item wrapperCol={{ offset: 20, span: 4 }}>
                        <Button type="primary" htmlType="submit">
                        提交
                        </Button>
                    </Form.Item>
                </Form>
                {/* <FormCom 
                    onRef={this.onFormRef} 
                    onBlur={this.onBlurEvent} 
                    formItem={this.state.formItem} 
                    formLayout={this.state.formLayout} 
                    formConfig={this.state.formConfig} 
                    submit={this.submit}>
                </FormCom> */}
            </Modal>
        )
    }
}

export default RenewModal;